import ApiFetchers from "@/apis/api_fetchers"
import { SetInitVerifyAtom, SetVerifyAtom, verifyAtom } from "@/pages/AccountPage/atoms/verify"
import { useAtom } from "jotai"
import _ from "lodash"
import { useNavigate } from "react-router-dom"
import { toast } from "react-toastify"
import { useCallback } from "react"

const sleep = (delay: number | undefined) => new Promise((resolve) => setTimeout(resolve, delay))

export function useEmail() {
    const navigator = useNavigate()
    const [verifyData] = useAtom(verifyAtom)
    const [, setVerifyData] = useAtom(SetVerifyAtom)
    const [, setInitVerifyData] = useAtom(SetInitVerifyAtom)
    const isEmailForget =
        verifyData && verifyData?.field === "email" && verifyData?.type === "forget"
    const handleSubmit = useCallback(
        async (values: { email: string }) => {
            if (isEmailForget) {
                await sleep(500)
                const res = {
                    success: true,
                    data: {
                        id: "23472389472398472",
                    },
                }
                if (res.success) {
                    // setVerifyData((prev) => ({
                    //     ...prev,
                    //     otpId: res?.data?.id,
                    //     type: "forget",
                    //     field: "email",
                    //     email: values.email,
                    // }))
                    setVerifyData({
                        ...verifyData,
                        otpId: res?.data?.id,
                        type: "forget",
                        field: "email",
                        email: values.email,
                    })
                }
                navigator("/forgetPassword/verify/verify")
            } else {
                const res = await ApiFetchers.refUpdateDetail({ record: values })

                if (res) {
                    setInitVerifyData()
                    navigator("/s-account")
                } else {
                    toast("Internal Server Error")
                    setTimeout(() => {
                        setInitVerifyData()
                        navigator("/s-account")
                    }, 800)
                }
            }
        },
        [verifyData, setVerifyData, setInitVerifyData, navigator, isEmailForget],
    )

    const throttledSubmit = useCallback(
        (values: { email: string }) => {
            const throttled = _.throttle((v: { email: string }) => handleSubmit(v), 5000)
            throttled(values)
        },
        [handleSubmit],
    )
    const handleBack = useCallback(() => {
        setInitVerifyData()
        if (isEmailForget) {
            navigator("/forgetPassword/")
        } else {
            navigator(-1)
        }
    }, [isEmailForget, navigator, setInitVerifyData])

    return {
        isEmailForget,
        onSubmit: throttledSubmit,
        onBack: handleBack,
    }
}
